package com.sdry.web.controller.lz;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sdry.utils.BaseUtils;
import com.sdry.web.controller.cb.ReportFormController;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.sdry.model.lz.Container;
import com.sdry.model.lz.Customer;
import com.sdry.model.lz.LzQueryCriteria;
import com.sdry.model.lz.Materiel;
import com.sdry.model.lz.Warehouse;
import com.sdry.model.lz.WarehouseRegion;
import com.sdry.model.lz.WarehouseRegionLocation;
import com.sdry.service.lz.MaterielService;
import com.sdry.utils.ExcelUtils;
import com.sdry.utils.ResponseUtil;

/**
 * @ClassName MaterielController
 * @Description 物料信息
 * @Author lz
 * @Date 2019年4月15日 17:37:17
 * @Version 1.0
 */
@Controller
@RequestMapping("/materiel")
public class MaterielController {

    public static final Integer AFFECT_ROW = 0;

    public static Logger logger = LogManager.getLogger(MaterielController.class);

    @Resource
    MaterielService materielService;

    /**
     * 物料新增
     * 多仓库添加 cb_2019-11-6 14:51:30
     * @param response
     * @param materiel
     */
    @RequestMapping("/addMateriel")
    public void addMateriel(HttpServletResponse response, Materiel materiel){
        logger.info("物料新增 , 多仓库添加 cb_2019-11-6 14:51:30");
        try {
            Long affectRow = materielService.addMateriel(materiel);
            //物料与仓库绑定时修改客户与仓库关联表的状态
            materielService.updateCustomerWarehouseStatus(materiel);
            ResponseUtil.write(response, affectRow);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据ID删除该行数据
     * @param response
     * @param idArr
     */
    @RequestMapping("/deleteMaterielById")
    public void deleteMaterielById(HttpServletResponse response, @RequestParam("idArr[]") String[] idArr){
        if(idArr.length > 0) {
            for (int i = 0; i < idArr.length; i++) {
                Long affectRow = materielService.deleteMaterielById(Long.parseLong(idArr[i]));
                if (affectRow > AFFECT_ROW) {
                    try {
                        ResponseUtil.write(response, affectRow);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        ResponseUtil.write(response, AFFECT_ROW);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 修改物料
     * @param response
     */
    @RequestMapping("/updateMateriel")
    public void updateMateriel(HttpServletResponse response, Materiel materiel) {
        Long affectRow = materielService.updateMateriel(materiel);
        if(affectRow > AFFECT_ROW){
            try {
                ResponseUtil.write(response, affectRow);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                ResponseUtil.write(response, "");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 分页查询物料表
     * 说明:改为多仓库版本，注释为原来代码，2019年11月6日10:21:02
     * @param criteria 条件
     * @return
     */
    @RequestMapping("/queryMaterielCriteria")
    @ResponseBody
    public Map<String,Object> queryMaterielCriteria(LzQueryCriteria criteria)  {
        String keyword01 = criteria.getKeyword01();
        String keyword02 = criteria.getKeyword02();
        String keyword03 = criteria.getKeyword03();
        String keyword04 = criteria.getKeyword04();
        if(keyword01 == null){
            keyword01 = "";
        }
        if(keyword02 == null){
            keyword02 = "";
        }
        if(keyword03 == null){
            keyword03 = "";
        }
        if(keyword04 == null){
            keyword04 = "";
        }
        criteria.setKeyword01(keyword01);
        criteria.setKeyword02(keyword02);
        criteria.setKeyword03(keyword03);
        criteria.setKeyword04(keyword04);
        try {
        logger.info("获取基础信息分页物料信息,改为多仓库版本，注释为原来代码，cb_2019年11月6日10:21:02   LzQueryCriteria"+JSONArray.fromObject(criteria));
        List<Materiel> materielList = materielService.queryMaterielCriteria(criteria);
        int count = materielService.countMaterielCriteria(criteria);
        return BaseUtils.getDateTableResult(materielList,count);
        } catch (Exception e) {
            e.printStackTrace();
            return BaseUtils.getDateTableResult(new ArrayList<>(),10);
        }

        /*List<Materiel> materielList = materielService.queryMaterielCriteria(criteria);
        int count = materielService.countMaterielCriteria(criteria);
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = JSONArray.fromObject(materielList);
        jsonObject.put("code", AFFECT_ROW);
        jsonObject.put("data", jsonArray);
        jsonObject.put("count", count);
        try {
            ResponseUtil.write(response, jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }*/

    }



    /**
     * 查找所有容器
     * 多仓库版本，cb_2019-11-6 14:26:25
     * @param response
     * @throws Exception
     */
	@RequestMapping("/queryAllContainer")
	public void queryAllContainer(HttpServletResponse response) throws Exception{
	    logger.info("查找所有容器,,,,多仓库版本，cb_2019-11-6 14:26:25");
		List<Container> containerList = materielService.queryAllContainer();
		JSONArray jsonArray = JSONArray.fromObject(containerList);
		if (containerList.size() > 0) {
            ResponseUtil.write(response, jsonArray);
        } else {
            ResponseUtil.write(response, null);
        }
	}
	/**
	 * 绑定客户
	 * @param materiel
	 * @param response
	 */
	/*@RequestMapping("bindingCustomer")
	public void bindingCustomer(Materiel materiel,HttpServletResponse response){
		int affact = materielService.bindingCustomer(materiel);
		try {
			ResponseUtil.write(response, affact);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}*/
	/**
	 * 客户绑定仓库
	 * @param customer 客户实体
	 * @param response
	 */
	@RequestMapping("warehouseBindingWarehouse")
	public void warehouseBindingWarehouse(Customer customer, HttpServletResponse response){
		int affact = materielService.warehouseBindingWarehouse(customer);
		try {
			ResponseUtil.write(response, affact);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 仓库树
	 */
	@RequestMapping("wareTree")
	public void wareTree(HttpServletResponse response,String regionType){
		//仓库
		List<Warehouse> warehouse = materielService.selectAllWarehouse();
		JSONArray jsonArray1 =  new JSONArray();
		JSONArray jsonArray2 =  new JSONArray();
		JSONArray jsonArray3 =  new JSONArray();
		for (Warehouse w : warehouse) {
			JSONObject json=new JSONObject();
			JSONObject jsonemp=new JSONObject();
			JSONObject jsonempchild=new JSONObject();
			json.put("name", w.getWarehouse_name());
			json.put("value", w.getId());
			//库区
			List<WarehouseRegion> region = materielService.selectRegionByWareid(w.getId());
			for (WarehouseRegion r : region) {
				 jsonemp.put("name", r.getRegion_name());
				 jsonemp.put("value", r.getId());
				 if("0".equals(regionType)){
					 //库位
					 List<WarehouseRegionLocation> location = materielService.selectLocationByRegionid(r.getId());
					 for (WarehouseRegionLocation l : location) {
						 jsonempchild.put("name", l.getLocation_name());
						 jsonempchild.put("value", l.getId());
						 jsonArray3.add(jsonempchild);
						 jsonemp.put("children", jsonArray3);
					 }
				 }
				 jsonArray2.add(jsonemp);
				 json.put("children",jsonArray2);
			}
			jsonArray1.add(json);
		}
		JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", jsonArray1);
        try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据客户id查询关联表中的库区
	 * @param response
	 * @param customer_id 客户id
	 * @throws Exception
	 */
	@RequestMapping("/queryRegionByCustomerId")
	public void queryRegionByCustomerId(HttpServletResponse response, String customer_id) throws Exception{
		List<WarehouseRegion> warehouseRegionList = materielService.queryRegionByCustomerId(customer_id);
		JSONArray jsonArray = JSONArray.fromObject(warehouseRegionList);
		if (warehouseRegionList.size() > 0) {
            ResponseUtil.write(response, jsonArray);
        } else {
            ResponseUtil.write(response, null);
        }
	}

    /**
     * 查询所有库区，多仓库版本cb_2019年11月12日11:38:43
     * @param response
     * @param customer_id 客户id
     * @throws Exception
     */
    @RequestMapping("/queryRegionByCustomerId1")
    public void queryRegionByCustomerId1(HttpServletResponse response, String customer_id) throws Exception{
        logger.info("查询所有库区，多仓库版本cb_2019年11月12日11:38:43   customer_id="+customer_id);
        List<WarehouseRegion> warehouseRegionList = materielService.queryRegionByCustomerId1(customer_id);
        JSONArray jsonArray = JSONArray.fromObject(warehouseRegionList);
        if (warehouseRegionList.size() > 0) {
            ResponseUtil.write(response, jsonArray);
        } else {
            ResponseUtil.write(response, null);
        }
    }

    /**
     * 导出Excel
     * @param response
     * @throws UnsupportedEncodingException 
     * @throws Exception
     */
    @RequestMapping("/doExportall")
    public void doExportall(HttpServletResponse response ,LzQueryCriteria criteria) throws UnsupportedEncodingException{
        String keyword01 = criteria.getKeyword01();
        String keyword02 = criteria.getKeyword02();
        String keyword03 = criteria.getKeyword03();
        String keyword04 = criteria.getKeyword04();
        if(keyword01 == null){
            keyword01 = "";
        }
        if(keyword02 == null){
            keyword02 = "";
        }
        if(keyword03 == null){
            keyword03 = "";
        }
        if(keyword04 == null){
            keyword04 = "";
        }
        criteria.setKeyword01(keyword01);
        criteria.setKeyword02(keyword02);
        criteria.setKeyword03(keyword03);
        criteria.setKeyword04(keyword04);
        criteria.setLimit(10000);
        criteria.setPage(1);
        List<Materiel> materiels = materielService.queryMaterielCriteria(criteria);
        List<List<String>> lists = zhuanlist(materiels);
        ExcelUtils.export("物料所有数据",namess(), response, lists);
    }

    public List<String> namess() {
        List<String> list = new ArrayList<>();
        list.add("供应商名称");
        list.add("容器名称");
        list.add("库区名称");
        list.add("放置类型");
        list.add("物料名称");
        list.add("产品码");
        list.add("简码");
        list.add("是否质检");
        list.add("物料规格");
        list.add("物料型号");
        list.add("拆箱后的数量");
        list.add("出厂日期");
		
		  list.add("单位"); list.add("体积"); list.add("重量");
		  
		  list.add("收货地址"); list.add("出库频率"); list.add("包装数量");
		  
		  list.add("上限值"); list.add("下限值"); list.add("是否绑定托盘"); list.add("托盘类型");
		  list.add("备注");
		 
        return list;
    }

    /**
     * 根据导出数据表头把List<cuser>转List<List<String>>
     * @param materiels
     * @return
     */
    public List<List<String>> zhuanlist (List<Materiel> materiels){
        List<List<String>> lists = new ArrayList<>();
        for (Materiel materiel : materiels) {
            List<String> list = new ArrayList<>();
            list.add(materiel.getCustomer_name());
            list.add(materiel.getContainer_name());
            list.add(materiel.getRegion_name());
            if ( materiel.getPlacement_type().equals("0")) {
                list.add("货架");
            } else {
                list.add("平地");
            }
            list.add(materiel.getMateriel_name());
            list.add(materiel.getMateriel_num());
            list.add(materiel.getBrevity_num());
            if ( materiel.getIs_check()==0) {
                list.add("是");
            } else {
                list.add("否");
            }
            list.add(materiel.getMateriel_size());
            list.add(materiel.getMateriel_properties());
            list.add(materiel.getDevanning_num());
            list.add(materiel.getOut_date());
			list.add(materiel.getUnit()); 
			list.add(materiel.getVolume());
			list.add(materiel.getWeight());
			list.add(materiel.getDelivery_address());
			list.add(materiel.getOutgoing_frequency());
			list.add(materiel.getPacking_quantity());
			list.add(String.valueOf(materiel.getUpper_value()));
			list.add(String.valueOf(materiel.getLower_value())); 
			if ( materiel.getIs_bindtray()==0) { 
				list.add("是"); 
			} else { 
				list.add("否"); 
			}
			if ( materiel.getTray_type()==0) { 
				list.add("物理托盘"); 
			} else { 
				list.add("逻辑托盘"); 
			}
			list.add(materiel.getRemark());
            lists.add(list);
            list = null;
        }
        return lists;
    }

    /**
     * 导出Excel
     * 多仓库版本 cb_2019-11-6 15:18:42
     * @param request
     * @param response
     */
    @RequestMapping("/uplodeFile")
    public void importor(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        
        //获取仓库id
        Long wareHouseId = BaseUtils.getSession();
        logger.info("物料的导入Excel  ， 多仓库版本 cb_2019-11-6 15:18:42");

        String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/"+file.getOriginalFilename());
        File newFile=new File(savePath);
        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //取文件后缀
        String subfix = savePath.lastIndexOf(".")==-1? "" : savePath.substring(savePath.lastIndexOf(".")+1);
        //System.out.println(subfix);
        List<List<String>> lists = new ArrayList<>();
        //获取导入行数
        List<String> names = namess();
        int num = names.size();
        if(subfix.equals("xls")){
            try {
                lists = ExcelUtils.readXls(savePath, request, num);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if(subfix.equals("xlsx")){
            try {
                lists = ExcelUtils.readXlsx(savePath, request,num);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                response.getWriter().print("0");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        int flag = 1;
        if (lists != null&&lists.size()>0) {
            for (int i = 0; i < lists.size(); i++) {
                List<String> list = new ArrayList<>();
                list= lists.get(i);
                Materiel materiel=new Materiel();
                List<Materiel> ms=materielService.queryMaterielBybnum(list.get(5));
                if(ms.size()>0) {
                	
                	for (Materiel materiel2 : ms) {
                		 if(null != list.get(0)) {
                             long cid = materielService.queryCustnameByname(list.get(0).trim());
                              materiel2.setCustomer_id(cid);
                          } else {
                              materiel.setCustomer_id(null);
                          }
                          if (null != list.get(1)) {
                              long tid = materielService.queryContainerByName(list.get(1).trim());
                              materiel2.setContainer_id(tid);
                          } else {
                              materiel2.setContainer_id(null);
                          }
                          if (null != list.get(2)) {
                              long rid = materielService.queryRegionByname(list.get(2).trim());
                              materiel2.setRegion_id(rid);
                          } else {
                              materiel2.setRegion_id(null);
                          }
                          if ( list.get(3).trim().equals("货架")) {
                              materiel2.setPlacement_type("0");
                          } else {
                              materiel2.setPlacement_type("1");
                          }
                          materiel2.setMateriel_name(list.get(4));
                          materiel2.setMateriel_num(list.get(5));
                          materiel2.setBrevity_num(list.get(6));
                          if (list.get(7).trim().equals("是")) {
                              materiel2.setIs_check(0);
                          } else {
                              materiel2.setIs_check(1);
                          }
                          materiel2.setMateriel_size(list.get(8));
                          materiel2.setMateriel_properties(list.get(9));
                          materiel2.setDevanning_num(list.get(10));
                          materiel2.setOut_date(list.get(11));
                          materiel2.setUnit(list.get(12));
                          materiel2.setVolume(list.get(13));
                          materiel2.setWeight(list.get(14));
                          
                          //去收货地址、后面的集合序号改变 从15开始都减一
                          //materiel2.setDelivery_address(list.get(15));
                          materiel2.setOutgoing_frequency(list.get(15));
                          materiel2.setPacking_quantity(list.get(16));
                          
                          materiel2.setUpper_value(Integer.parseInt(list.get(17)));
                          materiel2.setLower_value(Integer.parseInt(list.get(18)));
                          if (list.get(19).trim().equals("是")) {
                              materiel2.setIs_bindtray(0);
                          } else {
                              materiel2.setIs_bindtray(1);
                          }
                          if (list.get(20).trim().equals("物理托盘")) {
                              materiel2.setTray_type(0);
                          } else {
                              materiel2.setTray_type(1);
                          }
                           materiel2.setRemark(list.get(22));
                           
                         
                           long affact = materielService.updateMateriel(materiel2);
                           materiel2 = null;
                           if (affact == 0) {
                               flag = 0;
                               break;
                           }
					}
                }else {
                if(null != list.get(0)) {
                   long cid = materielService.queryCustnameByname(list.get(0).trim());
                    materiel.setCustomer_id(cid);
                } else {
                    materiel.setCustomer_id(null);
                }
                if (null != list.get(1)) {
                    long tid = materielService.queryContainerByName(list.get(1).trim());
                    materiel.setContainer_id(tid);
                } else {
                    materiel.setContainer_id(null);
                }
                if (null != list.get(2)) {
                    long rid = materielService.queryRegionByname(list.get(2).trim());
                    materiel.setRegion_id(rid);
                } else {
                    materiel.setRegion_id(null);
                }
                if ( list.get(3).trim().equals("货架")) {
                    materiel.setPlacement_type("0");
                } else {
                    materiel.setPlacement_type("1");
                }
                materiel.setMateriel_name(list.get(4));
                materiel.setMateriel_num(list.get(5));
                materiel.setBrevity_num(list.get(6));
                if (list.get(7).trim().equals("是")) {
                    materiel.setIs_check(0);
                } else {
                    materiel.setIs_check(1);
                }
                materiel.setMateriel_size(list.get(8));
                materiel.setMateriel_properties(list.get(9));
                materiel.setDevanning_num(list.get(10));
                materiel.setOut_date(list.get(11));
                materiel.setUnit(list.get(12));
                materiel.setVolume(list.get(13));
                materiel.setWeight(list.get(14));
                //去收货地址、后面的集合序号改变 从15开始都减一
                //materiel.setDelivery_address(list.get(15));
                materiel.setOutgoing_frequency(list.get(15));
                materiel.setPacking_quantity(list.get(16));
                
                materiel.setUpper_value(Integer.parseInt(list.get(17)));
                materiel.setLower_value(Integer.parseInt(list.get(18)));
                if (list.get(19).trim().equals("是")) {
                    materiel.setIs_bindtray(0);
                } else {
                    materiel.setIs_bindtray(1);
                }
                if (list.get(20).trim().equals("物理托盘")) {
                    materiel.setTray_type(0);
                } else {
                    materiel.setTray_type(1);
                }
                 materiel.setRemark(list.get(22));

               //多仓库id
               materiel.setWareHouseId(wareHouseId);
                long affact = materielService.addMateriel(materiel);
                materiel = null;
                if (affact == 0) {
                    flag = 0;
                    break;
                }
                }
            }
        }
        try {
            response.getWriter().print(flag);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 根据库区id查询库区类型
     * @param region_id 库区id
     * @param response
     * @throws Exception
     */
    @RequestMapping("/queryRegionTypeById")
	public void queryRegionTypeById(String region_id, HttpServletResponse response) throws Exception{
		WarehouseRegion warehouseRegion = materielService.queryRegionTypeById(region_id);
		JSONArray jsonArray = JSONArray.fromObject(warehouseRegion);
		if (warehouseRegion != null) {
            ResponseUtil.write(response, jsonArray);
        } else {
            ResponseUtil.write(response, null);
        }
	}
}